package com.springboot.mybatis.common.base.back;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class BaseBackController {
    
    public Logger log = LogManager.getLogger(BaseBackController.class);

    /**
     * springboot默认是保留null的<br />
     * Fastjson的SerializerFeature序列化属性<br />
     * QuoteFieldNames———-输出key时是否使用双引号,默认为true <br />
     * WriteMapNullValue——–是否输出值为null的字段,默认为false <br />
     * WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null <br />
     * WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null <br />
     * WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null <br />
     * WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null
     *
     * @param object 被渲染的对象
     * @return 
     */
    public String returnJson(Object object) {
        return JSONObject.toJSONString(object);
    }
    
    public <T> T getRequestBodyToModel(HttpServletRequest request, Class<T> clazz){
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = request.getReader()) {
            char[] ch = new char[1024];
            int readCount;
            while ((readCount = br.read(ch)) != -1) {
                sb.append(ch, 0, readCount);
            }
            return JSON.parseObject(sb.toString(), clazz);
        } catch (IOException e) {
            try {
                return clazz.newInstance();
            } catch (InstantiationException | IllegalAccessException e1) {
                e1.printStackTrace();
                return null;
            }
        }
    }
    
}
